import React, {Component} from 'react';
import {Button, Row, Col, Form, Input, Table, Modal, Tree, Layout} from 'antd';
import {EditRoleManage} from "../components/EditComponent";
import {ButtonSubmit} from "../components/AddComponent";
import {requestUrl} from '../value';
import app from '../AppMethod';
import {menu} from "../value";
import {Consumer} from "../store";

const FormItem = Form.Item;
const TreeNode = Tree.TreeNode;
const {Content} = Layout;
const confirm = Modal.confirm;

//根据最顶层的数据所包含的字数据的ID和所有的分类ID比较，相同的则为他的子数据 循环权限
const loop = (menu, data) => {
    let menuList = [];
    data.map((item, idex) => {
        if (menu.menu_id === item.menu_parentid) {
            menuList.push(item);
            menu.subList = menuList;
            loop(item, data);
        } else {
            menuList = [];
        }
    })
}

class roleManage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            data: [
                {
                    role_id: '1',
                    role_name: '董事长',
                    role_creator: 'ddd',
                    role_isable: 1
                }
            ],
            pagination: {
                current: 1,
                pageSize: 10,
                total: 20
            },
            searchData: {},
            editVisible: false,
            addConfirmLoading: false,
            locationData: {
                address: '广东省佛山市三水区xxxxxx',
                latitude: '23.3333334',//纬度
                longitude: '150.333335'//经度
            },
            isAddValid: false,
            menuList: [],
            roleList: [],
            menu_id: [],
            occurMenuList: []
        }
    };

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };
    columns = [
        {
            title: '角色',
            dataIndex: 'role_name'
        },
        {
            title: '是否有效',
            dataIndex: 'role_isable',
            render: role_isable => {
                let text = '';
                if (role_isable == 1) {
                    text = '是';
                } else if (role_isable == 0) {
                    text = '否'
                }
                return (
                    <span>{text}</span>
                )
            }
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <span>
                    <EditRoleManage
                        data={data}
                        menuList={this.state.menuList}
                        title="修改权限" width="600px"
                        labelName="角色名"
                        refresh={() => this.handleRefresh()}
                    />
                    <span style={{color: '#f5222d', cursor: 'pointer', marginLeft: '10px'}}
                          onClick={() => this.handleDelete(data.role_id)}>删除</span>
                    </span>
                )
            }
        }
    ];

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
                <div>
                    <Row>
                        <ButtonSubmit
                            isVisible={this.state.isAddValid == null ? false : this.state.isAddValid}
                            title="添加权限" buttonText={'添加权限'} width="600px"
                            addConfirmLoading={this.state.addConfirmLoading}
                            click={(e) => this.handleCancel(true)}
                            clickOk={(e) => this.handleSubmit(e)}
                            clickCancel={(e) => this.handleCancel(false)}
                        >
                            <Row>
                                <Col offset={1} span={22}>
                                    <Form className="login-form">
                                        <FormItem label="角色名" {...this.formItemLayout}>
                                            {
                                                getFieldDecorator('role_name', {
                                                    rules: [{required: true, message: '请输入角色名'}]
                                                })(
                                                    <Input placeholder="请输入"/>
                                                )
                                            }
                                        </FormItem>
                                        <FormItem label="权限" required={true} {...this.formItemLayout}>
                                            <Layout style={{height: '100%', width: '200px'}}>
                                                <Content style={{height: '450px', overflow: 'scroll'}}>
                                                    <MenuList
                                                        occurMenuList={this.state.occurMenuList}
                                                        onConfirm={(select, value) => this.getTypeId(select, value)}
                                                        menuList={this.state.menuList}
                                                    />
                                                </Content>
                                            </Layout>
                                        </FormItem>
                                    </Form>
                                </Col>
                            </Row>
                        </ButtonSubmit>
                        <Button type="primary" style={{marginLeft: '10px'}}
                                onClick={() => this.handleRefresh()}
                        >
                            刷新
                        </Button>

                    </Row>
                    <Row style={{marginTop: '20px'}}>
                        <Col span={24}>
                            <Table
                                columns={this.columns}
                                rowKey={record => record.role_id}
                                dataSource={this.state.data}
                                pagination={this.state.pagination}
                                loading={this.state.loading}
                            />
                        </Col>
                    </Row>
                </div>
        )
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({menuType: "权限管理"});
        this.searchRoleList();
        this.handleSearchMenuList();
    };

    componentWillUnmount() {
        this.setState = (count, callback) => {
            return;
        };
    };

    /**
     * 查询菜单数据列表
     */
    handleSearchMenuList() {
        app.post(menu.SEARCH_MENULISTALL, {}).then(req => {
            if (req.code == 1) {
                let firstMenu = [];
                req.data.dataSet.map((item) => {
                    if (item.menu_level === 1) {
                        firstMenu.push(item);
                    }
                });
                firstMenu.map((item) => {
                    loop(item, req.data.dataSet);
                });
                this.setState({menuList: firstMenu});
            } else {
                this.setState({menuList: []});
                app.alert(req.msg, 'error', 3);
            }
        })
    }

    /**
     * 处理刷新操作事件
     */
    handleRefresh() {
        this.searchRoleList();
    };

    /**
     * 显示和隐藏弹框
     * @param visible
     */
    handleCancel(visible) {
        this.setState({isAddValid: visible});
    };

    /**
     * 获取分类子组件中的值
     * @param select
     * @param value
     */
    getTypeId(select, value) {
        this.setState({
            roleList: select,
            menu_id: value,
            occurMenuList: select
        })
    };

    /**
     * 处理删除操作按钮事件
     * @param role_id
     */
    handleDelete(role_id) {
        const _this = this;
        confirm({
            title: '',
            content: '确认是否删除这个角色？',
            onOk() {
                const serverUrl = requestUrl.DEL_ROLE;
                let param = {role_id: role_id};
                app.post(serverUrl, param).then((result) => {
                    if (result.code === 1) {
                        app.alert('删除成功', 'success', 3);
                        _this.searchRoleList();
                    } else {
                        app.alert(result.msg, 'error', 3);
                    }
                })
            },
            onCancel() {

            }
        })
    };

    /**
     * 处理添加权限按钮事件
     */
    handleSubmit() {
        this.props.form.validateFields((error, values) => {
            if (!error) {
                let menuData = this.state.menu_id;
                let len = menuData.length;
                let menu_id = "";
                for (let i = 0; i < len; i++) {
                    menu_id += menuData[i] + ",";
                }
                if (menu_id.length > 0) {
                    menu_id = menu_id.substr(0, menu_id.length - 1);
                }
                let data = {
                    role_name: values.role_name,
                    menu_id: menu_id,
                };
                console.log(menu_id);
                app.post(menu.ADD_ROLE, data).then((result) => {
                    if (result.code === 1) {
                        app.alert("添加成功", 'success', 3);
                        this.searchRoleList();
                        this.handleCancel(false);
                    } else {
                        app.alert(result.msg, 'error', 3);
                    }
                })
            }
        })
    };

    /**
     * 处理搜索角色列表事件
     */
    searchRoleList() {
        const serverUrl = requestUrl.SEARCH_ROLELIST;
        this.setState({loading: true});
        app.post(serverUrl, {}).then((result) => {
            if (result.code === 1) {
                const len = result.data.dataSet.length;
                const pagination = {
                    current: 1,
                    pageSize: 10,
                    total: len
                };
                this.setState({data: result.data.dataSet, pagination});
            } else {
                let pagination = {
                    current: 0,
                    pageSize: 0,
                    total: 0
                };
                this.setState({data: [], pagination});
                app.alert(result.msg, 'error', 3);
            }
            this.setState({loading: false});
        })
    }
};

//树形赋值 权限菜单
class MenuList extends Component {
    state = {
        menuList: [],
        roleList: []
    };

    render() {
        const loop = (data) => data.map((item, index) => {
            if (item.subList) {
                return <TreeNode title={item.menu_name} key={item.menu_key}
                                 value={item}>{loop(item.subList)}</TreeNode>;
            }
            if (item.menu_key) {
                return <TreeNode title={item.menu_name} key={item.menu_key} value={item} isLeaf={true}/>;
            }
            return <TreeNode title={item.menu_name} key={item.menu_key} value={item} isLeaf={true}/>
        });
        return (
            <span>
                <Tree
                    checkable
                    onCheck={this.onCheck}
                    onSelect={this.onSelect}
                    checkedKeys={this.props.occurMenuList}
                >
                    {loop(this.props.menuList)}
                </Tree>
            </span>
        )
    };

    onSelect = (selectedKeys, info) => {

    };

    /**
     * 处理选中树节点事件
     * @param checkedKeys
     * @param info
     */
    onCheck = (checkedKeys, info) => {
        const menuList = info.checkedNodes.map((item) => {
            return item.props.value.menu_id;
        });
        this.props.onConfirm(checkedKeys, menuList);
    };
}

const RoleManages = Form.create()(roleManage);
export default prop => (
    <Consumer>
        {
            props => (
                <RoleManages {...prop} {...props}/>
            )
        }
    </Consumer>
);